package com.zj.leetcode.easy;

/**
 * @program: algorithm
 * @description:
 * @author: Zhang Bo
 * @create: 2022-01-04 17:59
 **/
public class ReverseStringIi {
    public static void main(String[] args) {
        //         "bacdfeg"
        //          bacdfeg
        String s = "abcd";
        int k = 4;
        Solution solution = new ReverseStringIi().new Solution();
        System.out.println(solution.reverseStr(s, k));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String reverseStr(String s, int k) {

            char[] cs = s.toCharArray();

            int num = 0;

            int len = (cs.length - 1);
            while ((num + (2 * k)) <= len) {
                this.toChar(cs, num, (num + k));
                num = num + 2 * k;
            }

            int more = (cs.length - 1) - num;
            if (more < k) {
                this.toChar(cs, num, cs.length);
            }

            if (more < 2 * k && more >= k) {
                this.toChar(cs, num, num + k);
            }

            return String.valueOf(cs);
        }

        private char[] toChar(char[] c, int l, int r) {

            int count = 0;
            while (l + count < (r - l) / 2 + l) {
                char temp = c[l + count];
                c[l + count] = c[r - count - 1];
                c[r - count - 1] = temp;
                count++;
            }
            return c;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
